Java types convert to byte[] types and Blob types are described in detail

  • 2020-05-10 18:10:00
  • OfStack

In our program development, java.sql.Blob, byte[], InputStream are often used for mutual conversion, but in JDK API, API is not directly available to us, the following program fragment is mainly to realize the interchange between them util.

1. byte [] = > Blob

We can achieve this through the presentation method provided by Hibernate, such as:

org. hibernate. Hibernate. Hibernate. createBlob (new byte [1024]).

2. Blob = > byte[]

Currently, no 1 point API is available, so we have to implement it by ourselves. Here's an example:


 /**

  *  the Blob Type conversion to byte An array type 

  * @param blob

  * @return

  */

  private byte[] blobToBytes(Blob blob) {

  BufferedInputStream is = null;

  try {

  is = new BufferedInputStream(blob.getBinaryStream());

  byte[] bytes = new byte[(int) blob.length()];

  int len = bytes.length;

  int offset = 0;

  int read = 0;

  while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {

  offset += read;

  }

  return bytes;

  } catch (Exception e) {

  return null;

  } finally {

  try {

  is.close();

  is = null;

  } catch (IOException e) {

  return null;

  }

  }

  }

3. InputStream = > byte[]


 private byte[] InputStreamToByte(InputStream is) throws IOException {

  ByteArrayOutputStream bytestream = new ByteArrayOutputStream();

  int ch;

  while ((ch = is.read()) != -1) {

  bytestream.write(ch);

  }

  byte imgdata[] = bytestream.toByteArray();

  bytestream.close();

  return imgdata;

  }

4. byte [] = > InputStream

The conversion from byte[] to inputStream is simple: InputStream is = new ByteArrayInputStream(new byte[1024]);

5. InputStream = > Blob

API: Hibernate.createBlob (new FileInputStream(" can be image/file path "));

6. Blob = > InputStream

Blog to flow, can be directly called through the provided API: new Blob().getBinaryStream();

The above section can be used as a reference for readers.

              thanks for reading, hope to help you, thank you for your support of this site!


Related articles: